﻿using System;
using System.Windows.Browser;

namespace Twilight.TwitterData
{
    [ScriptableType]
    public class TwitterDataProvider : BaseDataProvider
    {
        #region CallbackScript
        private const string CallbackScriptFormat = @"function twitterCallback2(json) {{ 
    var pluginObject = document.getElementById('{0}');
    pluginObject.Content.TwitterReader.TwitterCallback(json);
 }}";
        #endregion

        private HtmlElement jsonScript;
        private HtmlElement head;

        private void AddTwitterJsonScriptToHead()
        {
            if (jsonScript != null)
            {
                head.RemoveChild(jsonScript);
            }

            jsonScript = HtmlPage.Document.CreateElement("script");
            jsonScript.SetProperty("type", "text/javascript");
            jsonScript.SetProperty("src", string.Format("http://twitter.com/statuses/user_timeline/{0}.json?callback=twitterCallback2&count={1}&timestamp={2}", Username, Count, DateTime.Now.Ticks));

            head.AppendChild(jsonScript);
        }

        [ScriptableMember]
        public void TwitterCallback(ScriptObject json)
        {
            OnTweetsUpdated(json.ConvertTo<Tweet[]>());
        }

        public override void Initialize(string username, string count)
        {
            base.Initialize(username, count);

            HtmlPage.RegisterScriptableObject("TwitterReader", this);

            head = HtmlPage.Document.GetElementsByTagName("head")[0] as HtmlElement;

            string id = HtmlPage.Plugin.GetAttribute("id");  

            HtmlElement callbackScript = HtmlPage.Document.CreateElement("script");
            callbackScript.SetProperty("type", "text/javascript");
            callbackScript.SetProperty("text", string.Format(CallbackScriptFormat, id));
            head.AppendChild(callbackScript);

            AddTwitterJsonScriptToHead();
        }

        protected override void timer_Tick(object sender, EventArgs e)
        {
            AddTwitterJsonScriptToHead();
        }
    }
}
